<template>
  <div
      v-bind:class="{'outline-input-box':(startId == 'leaveStartTime' && endId == 'leaveEndTime')}">
    <li>
      <div class="item-content item-input">
        <div class="item-inner">
          <div class="item-title item-label">{{ startPlaceholder }}</div>
          <div class="item-input-wrap">
            <input type="text" name="start_time"
                   :placeholder="'选择' + startPlaceholder"
                   :id="startId"
                   readonly :disabled="inputDisabled?inputDisabled:false">
          </div>
        </div>
      </div>
    </li>
    <li>
      <div class="item-content item-input">
        <div class="item-inner">
          <div class="item-title item-label">{{ endPlaceholder }}</div>
          <div class="item-input-wrap">
            <input type="text" name="end_time"
                   :placeholder="'选择'+endPlaceholder"
                   :id="endId" readonly
                   :disabled="inputDisabled?inputDisabled:false">
          </div>
        </div>
      </div>
    </li>
  </div>
</template>

<script>
  import DateUtils from '../../js/mod.date';
  import ToastUtils from '../../mod/utils.toast';
  import PickerUtils from '../../mod/utils.picker';

  export default {
    props: ['startPlaceholder', 'endPlaceholder', 'startTime', 'endTime',
      'startId', 'endId', 'inputDisabled'],
    data() {
      return {
        systemTheme: 'md',
        startPicker: null,
        endPicker: null,

        preEndTime: '',

        monthValueArr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
        monthDisplayArr: ('01 02 03 04 05 06 07 08 09 10 11 12').split(' '),
        dayValueArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
          18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
        dayDisplayArr: ('01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31').split(
            ' '),
        hourValueArr: (() => {
          let arr = [];
          for (let i = 0; i <= 23; i++) {
            arr.push(i);
            // arr.push(i < 10 ? '0' + i : i);
          }
          return arr;
        })(),
        hourDisplayArr: (() => {
          let arr = [];
          for (let i = 0; i <= 23; i++) {
            arr.push(DateUtils.fix(i, 2));
          }
          return arr;
        })(),
        minuteValueArr: (() => {
          let arr = [];
          for (let i = 0; i <= 59; i++) {
            arr.push(i);
            // arr.push(i < 10 ? '0' + i : i);
          }
          return arr;
        })(),
        minuteDisplayArr: (() => {
          let arr = [];
          for (let i = 0; i <= 59; i++) {
            arr.push(DateUtils.fix(i, 2));
          }
          return arr;
        })(),
      }
    },
    watch: {
      startTime() {
        let _this = this;
        console.log('======' + _this.startTime);
        let startTimeInitVal = _this.getInitDatetimeBy('#' + _this.startId);
        if (_this.startPicker) {
          _this.startPicker.setValue(startTimeInitVal, 100);
        }
        let endTimeInitVal = _this.getInitDatetimeBy('#' + _this.endId);
        if (_this.endPicker) {
          _this.endPicker.setValue(endTimeInitVal, 100);
        }

        _this.checkStartAndEndTime();
      },
      endTime() {
        let _this = this;
        console.log('======' + _this.endTime);
        _this.checkStartAndEndTime();
      },
    },
    mounted: function () {
      let _this = this;
      this.$f7ready((f7) => {
        _this.systemTheme = _this.$f7.theme || 'md';
        _this.selectedDatetime('#' + _this.startId);
        _this.selectedDatetime('#' + _this.endId);
      });
    },
    methods: {
      checkStartAndEndTime() {
        let _this = this;
        let startDateTime = _this.startTime || '';
        let endDateTime = _this.endTime || '';
        let preEndDateTime = _this.preEndTime || '';
        switch (_this.systemTheme) {
          case 'md':
            break;
          case 'ios':
            startDateTime = startDateTime.replace(/-/g, '/');
            endDateTime = endDateTime.replace(/-/g, '/');
            preEndDateTime = preEndDateTime.replace(/-/g, '/');
            break;
        }
        let startTimestamp = new Date(startDateTime).getTime();
        let endTimestamp = new Date(endDateTime).getTime();

        if (endTimestamp - startTimestamp < 0) {
          let preEndTimestamp = (preEndDateTime != '') ?
              new Date(preEndDateTime) : null;
          if (preEndTimestamp && preEndTimestamp - startTimestamp > 0) {
            if (_this.endPicker) {
              let preEndTimeVal = _this.getInitDatetimeBy('#' + _this.endId,
                  _this.preEndTime);
              _this.endPicker.setValue(preEndTimeVal, 100);
              _this.$emit('changeEndTime', _this.preEndTime);
              ToastUtils.toast.show(ToastUtils.param.toast({
                text: _this.endPlaceholder + '不能早于' + _this.startPlaceholder
              }));
            }
          } else {
            let finishEndTimeObj = new Date(new Date(startDateTime).getTime()
                + 1 * 60 * 60 * 1000);
            let finishEndTimeStr = DateUtils.getFormatDateTime(
                finishEndTimeObj);
            let finishEndTimeVal = _this.getInitDatetimeBy('#' + _this.endId,
                finishEndTimeStr);
            if (_this.endPicker) {
              _this.endPicker.setValue(finishEndTimeVal, 100);
              _this.$emit('changeEndTime', finishEndTimeStr);
            }
          }
        }
      },
      selectedDatetime: function (_inputElement) {
        let _this = this;
        let initValue = _this.getInitDatetimeBy(_inputElement);

        let resDateTimeStr = initValue[0] + '-'
            + _this.monthDisplayArr[initValue[1]] + '-'
            + _this.dayDisplayArr[initValue[2] - 1] + ' ' + DateUtils.fix(
                initValue[3], 2) + ':' + DateUtils.fix(initValue[4], 2);
        switch (_inputElement) {
          case '#' + _this.startId:
            _this.$emit('changeStartTime', resDateTimeStr);
            break;
          case '#' + _this.endId:
            _this.preEndTime = _this.endTime ? _this.endTime : '';
            _this.$emit('changeEndTime', resDateTimeStr);
            break;
        }

        // console.log('++++++' + JSON.stringify(initValue))
        // ToastUtils.toast.show(ToastUtils.param.toast(
        //     {text: JSON.stringify(initValue)}));
        let params = {
          inputEl: _inputElement,
          toolbar: true,
          rotateEffect: true,
          value: initValue,
          formatValue: function (values, displayValues) {
            let month_value = parseInt(values[1]) + 1;
            month_value = DateUtils.fix(month_value, 2);
            return displayValues[0] + '-' + month_value + '-' + displayValues[2]
                + ' ' + displayValues[3] + ':' + displayValues[4];
          },
          cols: [
            // Years
            {
              values: (function () {
                let arr = [];
                for (let i = 1950; i <= 2030; i++) {
                  arr.push(i);
                }
                return arr;
              })(),
            },
            // Space divider
            {
              divider: true,
              content: ' '
            },
            // Months
            {
              values: _this.monthValueArr,
              displayValues: _this.monthDisplayArr,
              textAlign: 'left'
            },
            // Space divider
            {
              divider: true,
              content: ' '
            },
            // Days
            {
              values: _this.dayValueArr,
              displayValues: _this.dayDisplayArr
            },
            // Space divider
            {
              divider: true,
              content: ' '
            },
            // Hours
            {
              values: _this.hourValueArr,
              displayValues: _this.hourDisplayArr,
            },
            // Divider
            {
              divider: true,
              content: ':'
            },
            // Minutes
            {
              values: _this.minuteValueArr,
              displayValues: _this.minuteDisplayArr,
            }
          ],
          on: {
            init(picker) {
              // picker.setValue(initValue);
              console.log(picker.getValue());
              // AlertUtils.alert.show(AlertUtils.param.alert({
              //   title: JSON.stringify(picker.getValue()),
              //   buttons: [{}],
              // }));
            },
            open(picker) {
              _this.$$('input').blur();
              // AlertUtils.alert.show(AlertUtils.param.alert({
              //   title: JSON.stringify(picker.getValue()),
              //   buttons: [{}],
              // }));
            },
            change: function (picker, values, displayValues) {
              let daysInMonth = new Date(picker.value[0], picker.value[1] * 1
                  + 1, 0).getDate();
              // console.log()
              if (values[2] > daysInMonth) {
                picker.cols[2].setValue(daysInMonth, 100);
              }
            },
            closed: function (picker) {
              if (_inputElement == '#' + _this.startId) {
                let currentVal = _this.$$(_inputElement).val();
                _this.$emit('changeStartTime', currentVal);
              } else if (_inputElement == '#' + _this.endId) {
                _this.preEndTime = _this.endTime ? _this.endTime : '';
                let currentVal = _this.$$(_inputElement).val();
                _this.$emit('changeEndTime', currentVal);
              }
            }
          },
        };
        let pickerInline = PickerUtils.picker.show(
            PickerUtils.param.picker(params));
        switch (_inputElement) {
          case '#' + _this.startId:
            _this.startPicker = pickerInline;
            break;
          case '#' + _this.endId:
            _this.endPicker = pickerInline;
            break;
        }
      },
      initStartDateTimeObjBy() {
        let _this = this;
        let resDateObj = null;
        let nowDateObj = new Date();
        let now_hour = nowDateObj.getHours();
        let start_hour = parseInt(now_hour) + 1;
        if (now_hour == 23) {
          let nextDateObj = new Date(nowDateObj.getTime() + 24 * 60 * 60
              * 1000);
          let next_year = nextDateObj.getFullYear();
          let next_month = nextDateObj.getMonth();
          let next_day = nextDateObj.getDate();
          start_hour = 8;
          resDateObj = new Date(next_year, next_month, next_day, start_hour, 0,
              0);
        } else {
          let now_year = nowDateObj.getFullYear();
          let now_month = nowDateObj.getMonth();
          let now_day = nowDateObj.getDate();
          resDateObj = new Date(now_year, now_month, now_day, start_hour, 0, 0);
        }
        return resDateObj;
      },
      getInitDatetimeBy: function (_inputElement, _timeStr) {
        let _this = this;
        let dayObj = null;
        if (_timeStr && _timeStr != '') {
          _timeStr = (_this.systemTheme != 'md') ?
              _timeStr.replace(/-/g, '/') : _timeStr;
          dayObj = new Date(_timeStr);
        } else {
          let startDateTime = '';
          let endDateTime = '';
          switch (_inputElement) {
            case '#' + _this.startId:
              if (_this.startTime != '') {
                startDateTime = (_this.systemTheme != 'md') ?
                    _this.startTime.replace(/-/g, '/') : _this.startTime;
                dayObj = new Date(startDateTime);
              } else {
                // dayObj = new Date();
                dayObj = _this.initStartDateTimeObjBy();
              }
              break;
            case '#' + _this.endId:
              if (_this.endTime != '') {
                endDateTime = (_this.systemTheme != 'md') ?
                    _this.endTime.replace(/-/g, '/') : _this.endTime;
                dayObj = new Date(endDateTime);
              } else {
                let startObj = null;
                if (_this.startTime != '') {
                  startDateTime = (_this.systemTheme != 'md') ?
                      _this.startTime.replace(/-/g, '/') : _this.startTime;
                  startObj = new Date(_this.startTime);
                } else {
                  // startObj = new Date();
                  startObj = _this.initStartDateTimeObjBy();
                }
                dayObj = new Date(startObj.getTime() + 1 * 60 * 60 * 1000);
              }
              break;
          }
        }
        let resDatetimeArr = [];
        let year = dayObj.getFullYear();
        let month = dayObj.getMonth();
        let day = dayObj.getDate();
        let hour = dayObj.getHours();
        let minute = dayObj.getMinutes();
        resDatetimeArr.push(year);
        resDatetimeArr.push(month);
        resDatetimeArr.push(day);
        resDatetimeArr.push(hour);
        resDatetimeArr.push(minute);
        return resDatetimeArr;
      },
    }
  }
</script>

<style scoped>
  .outline-input-box li .item-input-wrap:after {
    height: 0px;
  }

  .outline-input-box li .item-input-wrap input {
    border: 1px solid #e5e5e5;
    padding-left: 8px;
    padding-right: 8px;
  }
</style>
